package com.theaf.core.utils;

import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ReferenceConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * 系统服务工具类
 * @author admin
 *
 */
public class SpringUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if(SpringUtils.applicationContext == null) {
            SpringUtils.applicationContext = applicationContext;
        }
    }

    //获取applicationContext
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    //通过name获取 Bean.
    public static Object getBean(String name){
        return getApplicationContext().getBean(name);
    }

    //通过class获取Bean.
    public static <T> T getBean(Class<T> clazz){
        return getApplicationContext().getBean(clazz);
    }

    //通过name,以及Clazz返回指定的Bean
    public static <T> T getBean(String name,Class<T> clazz){
        return getApplicationContext().getBean(name, clazz);
    }

    /*@Value("${spring.dubbo.registry.address}")
    private String zookeeperUrl;
    @Value("${spring.dubbo.application.name}")
    private String appName;*/

    public static <T> T getDubboService(Class<?> interf,String version){
        ApplicationConfig application = new ApplicationConfig();
        application.setName(applicationContext.getEnvironment().getProperty("spring.dubbo.application.name"));
        RegistryConfig registry = new RegistryConfig();
        registry.setProtocol(applicationContext.getEnvironment().getProperty("spring.dubbo.protocol.name"));
        registry.setPort(Integer.parseInt(applicationContext.getEnvironment().getProperty("spring.dubbo.protocol.port")));
        registry.setAddress(applicationContext.getEnvironment().getProperty("spring.dubbo.registry.address"));
        ReferenceConfig<T> rc = new ReferenceConfig<T>();
        rc.setApplication(application);
        rc.setRegistry(registry);
        rc.setInterface(interf);
        rc.setTimeout(Integer.parseInt(applicationContext.getEnvironment().getProperty("spring.dubbo.timeout")));
        rc.setVersion(version);
        return rc.get();
    }

    public static <T> T getDubboService(Class<?> interf){
        return getDubboService(interf,null);
    }

    public static void main(String[] args){
        String s = "/dta/sfsf/asfsf".replaceAll("\\{\\S+\\}","\\S+");
        System.out.println(s);
        String t = "/dta/sfsf/asfsf";
        System.out.println(t.matches(s));
    }

}
